package com.kun.stringtofile.service;

import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import java.io.*;
import java.lang.reflect.Array;
import java.util.Arrays;

@Service(value = "fileService")
public class GetStringOfFile {
    
    final static char[] digits = { '0', '1' };

    public String getFileString(String fileName) throws IOException {
        String path = ResourceUtils.getURL("classpath:").getPath()+ getFilePath(fileName);
        System.out.println(path);
        File fin = new File(path);
        byte[] buffer = new byte[1024];
        FileInputStream fis = new FileInputStream(fin);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        int i = 0;
        StringBuffer sb = new StringBuffer();
        while((i = fis.read(buffer)) != -1){
            bos.write(buffer,0,i);
        }
        byte[] result = bos.toByteArray();
        for (byte item:result) {
            sb.append(toBinaryString(item));
        }
        return sb.toString();
    }

    private String getFilePath(String name){
        if (name == null || name.isEmpty()){
            name = "demo.txt";
        }
        return "static/"+name;
    }

    public static String toBinaryString(byte b) {
        char[] buff = new char[8];
        int charPos = 8;
        do {
            buff[--charPos] = digits[b & 1];
            b >>>= 1;
        } while (charPos > 0);

        return new String(buff);
    }


    public static byte decodeBinaryString(String byteStr) {
        int re, len;

        if (null == byteStr) {
            return 0;
        }
        len = byteStr.length();

        if (len != 4 && len != 8) {
            return 0;
        }

        if (len == 8) {// 8 bit处理
            if (byteStr.charAt(0) == '0') {// 正数
                re = Integer.parseInt(byteStr, 2);
            } else {// 负数
                re = Integer.parseInt(byteStr, 2) - 256;
            }
        } else {//4 bit处理
            re = Integer.parseInt(byteStr, 2);
        }

        return (byte) re;
    }

}
